const { checkUsername, 
    checkUserRename ,
    checkRePassword,
    ,
    checkAge,
    saveUser,
    userLogin : userLoginService,
    getUserInfo
} = require('../services/user')

async function regist(ctx, next) {
  await ctx.render('regist')
}
async function login(ctx, next){

  await ctx.render('login')
}


async function userRegist(ctx, next) {
  const { username, password, rePassword, age, gender } = ctx.request.body

  let data = {
    status: 'success'
  }

  if (!checkUsername(username)) {
    data.status = 'failed'
    data.message = '用户名不合法'
  } else if (await checkUserRename(username)) {
    data.status = 'failed'
    data.message = '用户名重复'
  } else if(!checkPassword(password)){
    data.status = 'failed'
    data.message = '密码格式不正确'
  }else if(!checkRePassword(password,rePassword)){
    data.status = 'failed'
    data.message = '密码不一致'
  }else if(!checkAge(age)){
    data.status = 'failed'
    data.message = '年龄不合法'
  }else{
    await saveUser({ username, password, age, gender })
  }
  ctx.response.body = data
}
async function userLogin(ctx,next){

  const { username , password } = ctx.request.query

  let data = {
    status : 'success'
  }
 
  if(!checkUsername(username)){
    data.status = 'failed'
    data.message = '用户名不符合要求'
  }
  else if(!checkPassword(password)){
    data.status = 'failed'
    data.message = '密码不符合要求'
  }else{
    const result = await userLoginService({ username , password })

    if(!result){
      data.status = 'failed'
      data.message = '用户名密码不匹配'
    }else{
      data.id = result._id
    }
  }
  console.log('data ===>',data)
  ctx.response.body = data
}
async function userInfo(ctx,next){
  const{id}= ctx.request.query
  const result = await getUserInfo(id)
  console.log(result)
  await ctx.render('userInfo',{
    name:result.username,
    password:result.password,
    age:result.age
  })
}
module.exports = {
  regist,
  userRegist,
  login,
  userLogin,
  userInfo
}